<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary"
                     @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表 -->
      <el-table :data="roleList"
                border
                stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['vcenter', 'bdbottom', i1 === 0 ? 'bdtop' : '']"
                    v-for="(item1, i1) in scope.row.children"
                    :key="item1.psId">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable
                        @close="removeRightById(scope.row, item1.psId)">{{ item1.psName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级权限 -->
              <el-col :span="19">
                <el-row :class="[i2 !== 0 ? 'bdtop' : '', 'vcenter']"
                        v-for="(item2, i2) in item1.children"
                        :key="item2.psId">
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag closable
                            @close="removeRightById(scope.row, item2.psId)"
                            type="success">{{ item2.psName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18"
                          class="vcenter">
                    <el-tag v-for="item3 in item2.children"
                            :key="item3.psId"
                            type="warning"
                            closable
                            @close="removeRightById(scope.row, item3.psId)">{{ item3.psName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称"
                         prop="roleName"></el-table-column>
        <el-table-column label="角色描述"
                         prop="roleDesc"></el-table-column>
        <el-table-column label="操作"
                         width="300px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       @click="showEditDialog(scope.row.roleId)">编辑</el-button>
            <!-- 删除 -->
            <el-button type="danger"
                       icon="el-icon-delete"
                       size="mini"
                       @click="removeRoleById(scope.row.roleId)">删除</el-button>
            <!-- 分配权限 -->
            <el-button @click="showSetRightDialog(scope.row)"
                       type="warning"
                       icon="el-icon-setting"
                       size="mini">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色 -->
    <el-dialog title="添加角色"
               :visible.sync="addDialogVisible"
               width="40%"
               @close="addDialogClosed">
      <!-- 内容主体 -->
      <el-form ref="addFormRef"
               :model="addForm"
               :rules="addFormRules"
               label-width="70px">
        <el-form-item label="角色名"
                      prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述"
                      prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色 -->
    <el-dialog title="修改角色"
               :visible.sync="editDialogVisible"
               width="40%"
               @close="editDialogClosed">
      <!-- 内容主体 -->
      <el-form ref="editFormRef"
               :model="editForm"
               :rules="addFormRules"
               label-width="70px">
        <el-form-item label="角色名"
                      prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述"
                      prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限 -->
    <el-dialog title="分配权限"
               :visible.sync="setRightDialogVisible"
               width="40%"
               @close="setRightDialogClose">
      <!-- 树形结构 -->
      <el-tree :data="rightsList"
               :props="treeProps"
               :default-checked-keys="defKeys"
               default-expand-all
               node-key="psId"
               show-checkbox
               ref="treeRef"></el-tree>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 角色列表
      roleList: [],
      // 控制添加用户对话框
      addDialogVisible: false,
      // 控制修改用户对话框
      editDialogVisible: false,
      // 控制权限分配对话框
      setRightDialogVisible: false,
      // 添加用户
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑角色对象
      editForm: {},
      // 添加用户表单的验证规则
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          {
            min: 3,
            max: 11,
            message: '角色名应在2到10个字符之间',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 3,
            max: 11,
            message: '角色描述应在5到45个字符之间',
            trigger: 'blur'
          }
        ]
      },
      // 所以权限数据
      rightsList: [],
      // 树形控件绑定对象
      treeProps: {
        label: 'psName',
        children: 'children'
      },
      // 默认勾选的权限id
      defKeys: [],
      // 当前角色id
      roleId: ''
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    async getRoleList () {
      const { data: res } = await this.$http.get('/api/roles/getRoleList')
      if (res.meta.status !== 207) {
        return this.$message.error('获取角色信息失败！')
      } else {
        this.roleList = res.data
      }
    },
    // 监听添加角色对话框关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 监听修改角色对话框关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 添加角色
    addRole () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('/api/roles/addRole', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加角色失败！')
        } else {
          this.$message.success('添加角色成功！')
          this.addDialogVisible = false
          this.getRoleList()
        }
      })
    },
    // 展示修改用户对话框
    async showEditDialog (roleId) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('/api/roles/getById?roleId=' + roleId)
      if (res.meta.status !== 207) {
        return this.$message.error('查询角色信息失败！')
      } else {
        this.editForm = res.data
      }
    },
    // 修改角色
    editRole () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          '/api/roles/update',
          { roleId: this.editForm.roleId, roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc }
        )
        if (res.meta.status !== 203) {
          return this.$message.error('更新角色信息失败！')
        } else {
          this.editDialogVisible = false
          this.getRoleList()
          return this.$message.success('更新角色信息成功！')
        }
      })
    },
    // 根据id删除用户信息
    async removeRoleById (roleId) {
      // 弹框确认
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除操作！')
      } else {
        const { data: res } = await this.$http.get('/api/roles/del?roleId=' + roleId)
        if (res.meta.status !== 205) {
          return this.$message.error('删除角色失败！')
        } else {
          this.getRoleList()
          return this.$message.success('删除角色成功！')
        }
      }
    },
    // 根据Id删除对应权限
    async removeRightById (role, rightId) {
      // 弹框确认
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除操作！')
      } else {
        const { data: res } = await this.$http.get(
          '/api/roles/delRights?roleId=' + role.roleId + '&rightId=' + rightId
        )
        if (res.meta.status !== 205) {
          return this.$message.error('删除权限失败！')
        } else {
          role.children = res.data
          return this.$message.success('删除权限成功！')
        }
      }
    },
    // 展示权限分配弹窗
    async showSetRightDialog (role) {
      this.roleId = role.roleId
      // 获取权限数据
      const { data: res } = await this.$http.get('/api/rights?type=tree')
      if (res.meta.status !== 207) {
        return this.$message.error('获取权限数据失败！')
      } else {
        this.rightsList = res.data
      }

      // 递归获取三级权限id
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 递归获取当前角色三级权限
    getLeafKeys (node, arr) {
      // 没有children就是三级权限
      if (node.children === undefined || node.children.length <= 0) {
        return arr.push(node.psId)
      } else {
        // 递归一二级权限
        node.children.forEach(item => this.getLeafKeys(item, arr))
      }
    },
    // 监听权限分配对话框关闭事件
    setRightDialogClose () {
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        '/api/roles/setRights', { roleId: this.roleId, psIds: idStr })
      if (res.meta.status !== 203) {
        return this.$message.error('分配角色失败！')
      } else {
        this.getRoleList()
        this.setRightDialogVisible = false
        return this.$message.success('分配角色成功！')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
